﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Security.Claims;
using System.Security.Cryptography;
using Zhao.Arena.MiniProgram.Api.Utility.Jwt;
using Zhao.Common.Applet;
using Zhao.Common.Applet.Model;
using Zhao.Common.Helper;
using Zhao.IServer.User;
using Zhao.Models.AppletDto;
using Zhao.Models.Entity;

namespace Zhao.Arena.MiniProgram.Api.Controllers
{
    /// <summary>
    /// 用户登录API
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly WechatAPIClient _wechatAPIClient;
        private readonly IUsersServer _usersServer;
        private readonly JwtService _jwtService;
        private readonly IMemoryCache _memoryCache;

        public LoginController(
            WechatAPIClient wechatAPIClient, 
            IUsersServer usersServer,
            JwtService jwtService,
            IMemoryCache memoryCache)
        {
            this._wechatAPIClient = wechatAPIClient;
            this._usersServer = usersServer;
            this._jwtService = jwtService;
            this._memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取微信登录凭证
        /// </summary>
        /// <param name="code">微信登录code</param>
        /// <returns>登录凭证</returns>
        [HttpGet("token/{code}")]
        public async Task<JsonResult> GetToken(string code)
        {
            var result = new ApiResult<string>
            {
                Success = false
            };

            // 获取微信登录凭证
            var res = await _wechatAPIClient.GetCode2Session(code);
            if (res == null || res.errcode != 0)
            {
                result.Message = "获取微信登录凭证失败";
                return new JsonResult(result);
            }

            // 查询用户是否存在
            var user = await _usersServer.QueryAsync(x => x.OpenID == res.openid);
            if (user == null)
            {
                result.Message = "用户未注册";
                result.StatusCode = 401;
                return new JsonResult(result);
            }

            // 生成token
            var token = _jwtService.GenerateToken(user.UserID.ToString(), user.Username);

            // 存储token到缓存
            var cacheKey = $"token_{user.UserID}";
            _memoryCache.Set(cacheKey, token, TimeSpan.FromMinutes(30));

            result.Success = true;
            result.Data = token;
            return new JsonResult(result);
        }

        /// <summary>
        /// 根据code获取用户信息，检查请求头中的token
        /// </summary>
        /// <param name="code">微信登录code</param>
        /// <returns></returns>
        [HttpGet("{code}")]
        [Authorize]
        public async Task<JsonResult> Get(string code)
        {
            var result = new ApiResult<UserInfo>
            {
                Success = false,
            };

            // 获取微信登录信息
            var res = await _wechatAPIClient.GetCode2Session(code);

            if (res == null || res.errcode != 0)
            {
                result.Message = "非法用户";
                return new JsonResult(result);
            }

            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;

            //获取到id
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.Message = "缺少参数";
                result.StatusCode = 400;
                return new JsonResult(result);
            }

            int id = (int)idClaim.ToInt32();

            // 查询用户信息(做双重验证)
            var user = await _usersServer.QueryAsync(x => x.OpenID == res.openid && x.UserID==id);

            if (user == null)
            {
                result.Success = true;
                result.StatusCode = 401;
                result.Message = "账户或密码错误";
                return new JsonResult(result);
            }


            // 构建返回结果
            result.Data = new UserInfo
            {
                name = user.Username,
                image = user.Avatar,
                phone = user.Phone,
                balance = user.AccountBalance,
                sex = user.Sex,
            };

            result.Success = true;
            return new JsonResult(result);
        }

        [HttpPost("decryptPhone")]
        public async Task<JsonResult> DecryptPhone([FromBody]WeChatPhoneDecryptRequest request)
        {
            var result = new ApiResult<string>();
            //首先需要先获取token才能去请求解密手机号
            AccessToken accessToken = await _wechatAPIClient.GtoToKen();
            //获取到token之后就去请求API解密手机号
            PhoneInfoResult phoneInfo = await _wechatAPIClient.getUserPhoneNumberByCode(request.code, accessToken.access_token);
            result.StatusCode = phoneInfo.errcode;
            result.Message = phoneInfo.errmsg;
            result.Data = phoneInfo.phone_info.purePhoneNumber;

            return new JsonResult(result);
        }
    }
}
